package com.todd.studentms.servlet;

import cn.hutool.core.io.IoUtil;
import cn.hutool.db.Session;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sun.org.apache.xerces.internal.util.Status;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import com.todd.studentms.util.MyUtil;
import com.todd.studentms.util.Response;
import jdk.nashorn.internal.ir.CatchNode;
import lombok.SneakyThrows;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import sun.misc.IOUtils;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class EssentialServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) {
        PrintWriter out = null;
        try {
            res.setContentType("application/json;charset=utf-8");
            out = res.getWriter();
            String requestURI = req.getRequestURI();
            String requestMethod = req.getMethod().toUpperCase();
            Class<? extends EssentialServlet> cls = this.getClass();
            Object data = null;
            switch (requestMethod) {
                case "GET":
                case "POST":
                    String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
                    Method method = cls.getMethod(methodName, JSONObject.class, HttpServletRequest.class, HttpServletResponse.class);
                    JSONObject jsonObj = requestMethod.equals("GET") ? MyUtil.GETRequest2Json(req) : MyUtil.POSTRequest2Json(req);
//                    jsonObj.setDateFormat("yyyy-MM-dd");
                    System.out.println("AcceptJSON  >>> " + jsonObj);
                    data = method.invoke(this, jsonObj, req, res);
                    break;
                case "DELETE":
                    Method method1 = cls.getMethod("doDelete", String[].class, HttpServletRequest.class, HttpServletResponse.class);
                    // 转id数组
                    String[] ids = MyUtil.request2StringArr(req);
                    data = method1.invoke(this, ids, req, res);
                    break;
            }
            out.println(JSONUtil.toJsonPrettyStr(new Response(0, "success", data)));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            res.setStatus(404);
            out.println(JSONUtil.toJsonPrettyStr(new Response(1, e.getMessage(), null)));
        } catch (Exception e) {
            e.printStackTrace();
            out.println(JSONUtil.toJsonPrettyStr(new Response(1, e.getMessage(), null)));
        } finally {
            out.close();
        }
    }
}
